package cn.xiyan.baas.controller;


import cn.xiyan.baas.entity.FileEntity;
import cn.xiyan.baas.service.IFileService;
import cn.xiyan.baas.utils.Constant;
import cn.xiyan.baas.utils.RedisClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ruiyanglee
 * @since 2020-08-25
 */
@Api(tags = "文件信息接口")
@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {
    public static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Resource
    private RedisClient redisClient;
    @Resource
    private IFileService fileService;

    @GetMapping("/list/{userId}")
    @ApiOperation(value = "文件用户信息列表")
    // 获取参数
    public Object list(@PathVariable("userId") String userId) {
        List<FileEntity> list = fileService.findByUserId(userId);
        redisClient.set("/list", list);
        return list;
    }


    @PostMapping("/upload/{userId}")
    @ApiOperation(value = "文件上传")
    @ResponseBody
    public Object upload(@PathVariable("userId") String userId,
                         // @RequestParam(value = "file") MultipartFile file
                         MultipartHttpServletRequest request) {
        try {
            List<MultipartFile> files = request.getFiles("file");
//            MultipartFile file = request.getFile("file");
//            String id = "1296655841692495874";
            if (files != null && files.size() > 0) {
                for (MultipartFile file : files) {
                    log.info("start upload ...");
                    if (!file.isEmpty()) {
                        File fileSourcePath = new File(Constant.PATH);
                        if (!fileSourcePath.exists()) {
                            fileSourcePath.mkdirs();
                        }
                        // 获取原文件名称
                        String fileName = file.getOriginalFilename();
                        log.info("file name {}", fileName);
                        // 在服务器上指定存储文件
                        File targetFile = new File(fileSourcePath, fileName);
                        file.transferTo(targetFile);

                        log.info("upload end ....");
                        FileEntity fileEntity = new FileEntity();
                        fileEntity.setUserId(userId);
                        fileEntity.setFilePath(Constant.PATH + fileName);
                        fileService.save(fileEntity);
                    }
                }
                return "上传成功";
            }
            return "上传失败";
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
            return "上传失败";
        } catch (IOException e) {
            log.error(e.getMessage());
            return "上传失败";
        }
    }


    @ApiOperation(value = "文件下载")
    @GetMapping("/download/{fileId}")
    @ResponseBody
    public Object download(HttpServletResponse response,
                           @PathVariable("fileId") String id) {
        OutputStream os = null;
        BufferedInputStream bis = null;
        FileInputStream fis = null;
        try {
            FileEntity fileEntity = fileService.findById(id);
            if (fileEntity == null) {
                return "文件不存在";
            }
            String path = fileEntity.getFilePath();
            String fileName = StringUtils.substringAfterLast(path, "/");
            log.info("file name {}", fileName);
            File file = new File(path);
            if (!file.exists()) {
                Exception exception = new FileNotFoundException(path + "文件不存在");
                log.error(exception.getMessage());
                return "文件不存在";
            }

            // 对文件名进行utf-8编码
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            response.setContentType("application/force-download;charset=utf-8");
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);

            os = response.getOutputStream();

            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            return "下载成功";
        } catch (Exception e) {
            log.error(e.getMessage());
            return "下载失败";
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (bis != null) {
                    bis.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

}

